﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace LuckyCoding.Models;

public class FolderModel
{
    //public string ImagePath { get; set; }
    public List<FolderModel> Children { get; set; } = new ();
    //public string? Extension { get; set; }
    public string? Name { get; set; }
    public string? Location { get; set; }

    public FolderModel(string location,string[]? order = null)
    {
        Location = location;
        //Extension = Path.GetExtension(location);
        Name = Path.GetFileName(location);
        if (!Directory.Exists(location))
        {
            //ImagePath = Path.Combine(Coding.CodePath,"Assets","code.svg");
            return;
        }
        //ImagePath = Path.Combine(Coding.CodePath,"Assets","folder.svg");
        if (order == null)
        {
            var dir = new DirectoryInfo(location);
            var list = new List<string>();
            if (dir.GetFileSystemInfos().Any(x => x.Extension == ".gitignore"))
            {
                var s = dir.GetFileSystemInfos().FirstOrDefault(x => x.Extension == ".gitignore");
                if (s != null)
                {
                    list.AddRange(File.ReadAllLines(s.FullName).Select(line => line.Trim('/')));
                    if (list.Count != 0)
                    {
                        list.AddRange(new []{".git",s.Name,".idea",".vs",".vscode"});
                        order = list.ToArray();
                    }
                }
            }
            else
                order = new[] { ".git", ".idea", ".vs", ".vscode", "bin", "debug" };
        }
        Init(location,order);
    }

    private void Init(string location, string[]? order)
    {
        var dir = new DirectoryInfo(location);
        foreach (var info in dir.GetFileSystemInfos())
        {
            if (order != null && order.Any(x => x == info.Name)) continue;
            Children.Add(new FolderModel(info.FullName,order));
        }
    }
}

public static class Coding
{
    public static string CodePath
    {
        get
        {
            var directory = AppContext.BaseDirectory.Split(Path.DirectorySeparatorChar);
            var slice = new ArraySegment<string>(directory, 0, directory.Length - 4);
            return Path.Combine(slice.ToArray());
        }
    }
}